﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.Caching;

namespace Enter.DataProxy.Cache.Configuration
{
    internal class EntlibCache
    {
        public static readonly string FileString;
        private static CacheDependency dep;

        static EntlibCache()
        {
            FileString = GetFile();
        }

        /// <summary>
        /// 判断缓存文件是否修改 修改false
        /// </summary>
        /// <returns></returns>
        public static bool CheckCacheConfig()
        {
            if (!string.IsNullOrEmpty(FileString))
            {
                if (dep == null)
                {
                    SetFileCache();
                    return true;
                }
                if (dep.HasChanged)
                {
                    SetFileCache();
                    return false;
                }
                return true;
            }
            return false;
        }


        #region 私有方法

        /// <summary>
        /// 读取缓存配置文件
        /// </summary>
        /// <returns></returns>
        private static string GetFile()
        {
            string filename = null;

            if (filename == null)
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    filename = context.Server.MapPath("~/Cache.config");
                    if (!File.Exists(filename))
                    {
                        filename = context.Server.MapPath("/Cache.config");
                    }
                }
                else
                {
                    filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache.config");
                }
                if (!File.Exists(filename))
                {
                    filename = "";
                    // throw new DNTException("发生错误: 虚拟目录或网站根目录下没有正确的DataHelper.config文件");
                }
            }
            return filename;

        }


        private static void SetFileCache()
        {
            string file = FileString;
            if ((file != null) || (file.Length > 0))
            {
                dep = null;
                dep = new CacheDependency(file, DateTime.Now);
            }
        }
        #endregion

    }
}
